package com.posti.ciudaddelbache.core.net;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class URLBuilder {
  private final String baseUrl;
  private Map<String, String> parameters;

  public URLBuilder(String url) {
    this.parameters = new HashMap<String, String>();
    this.baseUrl = url;
  }

  public URLBuilder addParameter(String name, String value) {
    parameters.put(name, value);  //TODO: Encode!
    return this;
  }

  public String buildUrl() {
    StringBuilder builder = new StringBuilder();
    builder.append(baseUrl);

    if (!parameters.isEmpty()) {
      builder.append("?");
      for (Iterator<String> it = parameters.keySet().iterator(); it.hasNext();) {
        String name = it.next();
        builder.append(name);
        builder.append("=");
        builder.append(parameters.get(name));

        if (it.hasNext()) {
          builder.append("&");
        }
      }
    }

    return builder.toString();
  }
}
